import { login, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  shopName: ''
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_SHOP_NAME: (state, name) => {
    state.shopName = name
  }
}
const actions = {
  // login
  login ({ commit }, userInfo) {
    const username = userInfo.username.trim()
    return new Promise((resolve, reject) => {
      login({ seller_name: username, password: userInfo.password }).then(response => {
        // info
        const { token } = response.data
        setToken(token)
        commit('SET_TOKEN', token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  setTokenAction ({ commit }, token) {
    commit('SET_TOKEN', token)
  },
  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then((res) => {
        const { data } = res
        if (!data) {
          reject(new Error('Verification failed, please Login again.'))
        }
        const name = data.info.seller_name
        const shopName = data.info.shop_name
        commit('SET_NAME', name)
        commit('SET_SHOP_NAME', shopName)
        resolve(name)
      }).catch(error => {
        reject(error)
      })
    })
  },

  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
